#ifndef __EVENTLOOP_H__
#define __EVENTLOOP_H__

#include <functional>
#include <list>
#include <set>
#include <map>
#include <utility>
#include <stdint.h>
#include "Mutex.h"

typedef std::function<void()> Functor;
typedef std::function<void(int)> IO_Functor;
typedef std::pair<int64_t, Functor*> DelayEntry;

class EventLoop
{
public:
    EventLoop();
    ~EventLoop();

    void Loop();
    void Stop();

    void Run(Functor f);
    DelayEntry DelayRun(Functor f, double delay);
    void AbortDelayFunctor(DelayEntry &entry);

    void AddFd(int fd, int events, IO_Functor iocb);
    void ModFd(int fd, int events, IO_Functor iocb);
    void DelFd(int fd);

private:
    void AddFdInLoop(int fd, int events, IO_Functor iocb);
    void ModFdInLoop(int fd, int events, IO_Functor iocb);
    void DelFdInLoop(int fd);
    void EventHandler(int events);
    void TimerHandler(int events);
    void ResetTimer();

private:
    bool mLoop;
    Mutex mMutex;
    int mTimerfd;
    int mEventfd;
    int mEpollfd;

    std::list<Functor> mFunctors;
    std::set<DelayEntry> mDelayFunctors;
    std::map<int, IO_Functor> mIO_Functors;

private:
    EventLoop(const EventLoop&);
    EventLoop& operator=(const EventLoop&);
};

#endif
